<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG知识库系统</title>
    <link href="/static/bootstrap.min.css" rel="stylesheet">
    <style>
        .result-card {
            margin-bottom: 1rem;
            padding: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
        }
        .loading {
            display: none;
        }
        #searchHistory {
            position: fixed;
            top: 0px;
            right: 1rem;
            margin-right: 1rem ;
            width: 300px;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-radius: 4px;
            z-index: 1000;
            max-height: 80vh;
            overflow-y: auto;
        }
        .history-list {
            max-height: 120px;
            overflow: hidden;
            transition: max-height 0.3s ease-in-out;
        }
        .history-list.expanded {
            max-height: none;
        }
        .toggle-history {
            width: 100%;
            text-align: center;
            padding: 5px;
            margin-top: 5px;
            background: #f8f9fa;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .toggle-history:hover {
            background: #e9ecef;
        }
    </style>
    <script src="/static/vue.js"></script>
    <script src="/static/marked.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <h1 class="mb-4">RAG知识库系统</h1>
        
<a href="{{ url_for('docmanage') }}" class="btn btn-primary mb-4">知识库</a>
<a href="/upload_page" class="btn btn-primary mb-4">上传文档</a>
<a href="#" class="btn btn-warning mb-4" onclick="clearSessionContext()">清空会话</a>
<a href="/status" class="btn btn-secondary mb-4">状态统计</a>

        <!-- 搜索部分 -->
        <div class="card">
            <div class="card-body">
                <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" value="" id="useContext" checked>
                    <label class="form-check-label" for="useContext">
                        使用上下文
                    </label>
                </div>
                <div class="mb-3">
                    <label for="knowledgeBaseSelect" class="form-label">选择知识库</label>
                    <select class="form-select" id="knowledgeBaseSelect">
                        <option value="">不选择知识库</option>
                        <!-- 这里通过JavaScript动态填充选项 -->
                    </select>
                </div>
                <h5 class="card-title">知识库搜索</h5>
                <form id="searchForm" class="mb-3">
                    <div class="input-group">
                        <input type="text" class="form-control" id="searchQuery" placeholder="输入搜索内容..." required>
                        <button type="submit" class="btn btn-primary">
                            <span class="spinner-border spinner-border-sm loading" role="status" aria-hidden="true"></span>
                            搜索
                        </button>
                    </div>
                </form>
                <div id="searchResults"></div>
                <div id="searchResults"></div>
            </div>
        </div>
    </div>

    <!-- 历史搜索记录列表 -->
    <div id="searchHistory" class="mt-3">
        <h6 class="mb-2">历史搜索</h6>
        <div class="list-group history-list"></div>
        <button class="toggle-history" onclick="toggleHistory()">展开更多</button>
    </div>

    <script src="/static/bootstrap.bundle.min.js"></script>
    <script>


        // 搜索处理
        document.addEventListener('DOMContentLoaded', () => {
    loadKnowledgeBases();
    displaySearchHistory();
            displaySearchHistory();
            // 加载知识库列表
        async function loadKnowledgeBases() {
            try {
                const response = await fetch('/get_enabled_knowledge_bases');
                const data = await response.json();
                const select = document.getElementById('knowledgeBaseSelect');
                data.forEach(kb => {
                    const option = document.createElement('option');
                    option.value = kb.id;
                    option.textContent = kb.title;
                    select.appendChild(option);
                    select.selectedIndex = 1;
                });
            } catch (error) {
                console.error('加载知识库列表出错:', error);
            }
        }

        // 添加输入框焦点事件监听
            document.getElementById('searchQuery').addEventListener('focus', () => {
                displaySearchHistory();
            });
        });

        document.getElementById('searchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const form = e.target;
            const query = form.querySelector('#searchQuery').value;
            
            if (!query.trim()) {
                return;
            }

            // 添加到历史记录
            addToSearchHistory(query);
            await performSearch(query);
        });

        // 历史记录管理
        function addToSearchHistory(query) {
            const historyList = JSON.parse(localStorage.getItem('searchHistory') || '[]');
            // 移除已存在的相同查询
            const index = historyList.indexOf(query);
            if (index > -1) {
                historyList.splice(index, 1);
            }
            // 添加到开头
            historyList.unshift(query);
            // 保持最多20条记录
            if (historyList.length > 20) {
                historyList.pop();
            }
            localStorage.setItem('searchHistory', JSON.stringify(historyList));
            displaySearchHistory();
        }

        function displaySearchHistory() {
            const historyList = JSON.parse(localStorage.getItem('searchHistory') || '[]');
            const historyDiv = document.querySelector('#searchHistory .list-group');
            historyDiv.innerHTML = historyList.map(query => `
                <button type="button" class="list-group-item list-group-item-action" onclick="handleHistoryClick('${query.replace(/'/g, "'")}')">                    ${query}
                </button>
            `).join('');
            updateToggleButton();
        }

        function toggleHistory() {
            const historyList = document.querySelector('.history-list');
            const toggleBtn = document.querySelector('.toggle-history');
            historyList.classList.toggle('expanded');
            toggleBtn.textContent = historyList.classList.contains('expanded') ? '收起' : '展开更多';
        }

        function updateToggleButton() {
            const historyList = JSON.parse(localStorage.getItem('searchHistory') || '[]');
            const toggleBtn = document.querySelector('.toggle-history');
            toggleBtn.style.display = historyList.length > 3 ? 'block' : 'none';
        }

        async function handleHistoryClick(query) {
            document.getElementById('searchQuery').value = query;
            addToSearchHistory(query);
            await performSearch(query);
        }

        async function performSearch(query) {
            const submitBtn = document.querySelector('button[type="submit"]');
            const loading = submitBtn.querySelector('.loading');
            const resultsDiv = document.getElementById('searchResults');

            try {
                loading.style.display = 'inline-block';
                submitBtn.disabled = true;
                resultsDiv.innerHTML = '';

                // 获取或生成会话ID
                let sessionId = localStorage.getItem('sessionId');
                if (!sessionId) {
                    sessionId = crypto.randomUUID();
                    localStorage.setItem('sessionId', sessionId);
                }

                // 获取上下文
                const context = localStorage.getItem(sessionId) || '';
                const useContext = document.getElementById('useContext').checked;
const knowledgeBaseId = document.getElementById('knowledgeBaseSelect').value;

const bodyData = { 
    query: query,
    session_id: sessionId
};


if (useContext) {
    bodyData.context = context;
}
if (knowledgeBaseId) {
    bodyData.id = knowledgeBaseId;
}




                const response = await fetch('/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(bodyData)
                });


                

                const data = await response.json();

                // 更新上下文
                if (data && data.success && data.llm_response) {
                    localStorage.setItem(sessionId, context + '\n' + query + '\n' + data.llm_response);
                }

                if (data && data.success) {
                    displaySearchResults(data);
                } else {
                    showSearchError(data?.error || '搜索失败，请稍后重试');
                }
            } catch (error) {
                console.error('搜索请求出错:', error);
                showSearchError('搜索过程中发生错误，请稍后重试');
            } finally {
                loading.style.display = 'none';
                submitBtn.disabled = false;
            }
        }

        function displaySearchResults(data) {
            const resultsDiv = document.getElementById('searchResults');
            resultsDiv.innerHTML = '';

            if (!data || !data.success) {
                showSearchError(data.error || '搜索失败，请稍后重试');
                return;
            }

            const results = data.knowledge_results;
            if (!results?.documents?.[0]?.length) {
                resultsDiv.innerHTML = '<div class="alert alert-info">没有找到相关结果</div>';
                return;
            }

            // 显示大模型响应
            if (data.llm_response) {
                const llmResponseDiv = document.createElement('div');
                llmResponseDiv.className = 'result-card mb-4';
                llmResponseDiv.innerHTML = `
                    <div class="mb-2">
                        <strong>大模型回答:</strong>
                    </div>
                    <div>${marked.parse(data.llm_response)}</div>
                `;
                resultsDiv.appendChild(llmResponseDiv);
            }

            results.documents[0].forEach((doc, index) => {
                const resultCard = document.createElement('div');
                resultCard.className = 'result-card';
                let relevanceHtml = '';
                if (results.distances && results.distances[0]) {
                    relevanceHtml = `<div class="mb-2"><strong>相关度: ${Math.round(results.distances[0][index] * 100)}%</strong></div>`;
                }
                resultCard.innerHTML = `
                    ${relevanceHtml}
                    <div>${doc}</div>
                `;
                resultsDiv.appendChild(resultCard);
            });
        }

        function showStatus(message, type) {
            const statusDiv = document.getElementById('uploadStatus');
            statusDiv.className = `alert alert-${type}`;
            statusDiv.textContent = message;
            statusDiv.style.display = 'block';
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }

        

        function showSearchError(message) {
            const resultsDiv = document.getElementById('searchResults');
            resultsDiv.innerHTML = `<div class="alert alert-danger">${message}</div>`;
        }

        // 清空会话上下文
        function clearSessionContext() {
            const sessionId = localStorage.getItem('sessionId');
            if (sessionId) {
                localStorage.removeItem(sessionId);
            }
            // 创建临时通知元素
            const notificationDiv = document.createElement('div');
            notificationDiv.className = 'alert alert-success';
            notificationDiv.textContent = '会话上下文已清空';
            document.body.prepend(notificationDiv);
            // 5秒后移除通知
            setTimeout(() => {
                notificationDiv.remove();
            },2000);
        }
    </script>
</body>
</html>